package com.onlyxiahui.framework.json.validator.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.onlyxiahui.framework.json.validator.Validator;
import com.onlyxiahui.framework.json.validator.ValidatorError;
import com.onlyxiahui.framework.json.validator.ValidatorResult;

/**
 * 
 * Date 2018-12-26 17:18:43<br>
 * Description 
 * @author XiaHui<br>
 * @since 1.0.0
 */
public class JsonInStringArrayValidator implements Validator<JSONObject, Object> {

	@Override
	public ValidatorResult valid(JSONObject data, Object attribute, Object judge, String code, String message) {
		ValidatorResult vr = null;
		boolean mark = true;
		String[] valueArray = getArray(judge);
		if (null != attribute && null != judge) {
			String text = attribute.toString();

			mark = contains(valueArray, text);
		}
		if (!mark) {
			vr = new ValidatorResult();
			vr.setErrorCode(code == null ? this.getCode() : code);
			vr.setMessage(message == null ? this.getMessage(valueArray) : message);
		}
		return vr;
	}

	public String getMessage(String[] valueArray) {
		StringBuilder message = new StringBuilder("值只能在");
		message.append("[");
		if (null != valueArray) {
			int length = valueArray.length;
			for (int i = 0; i < length; i++) {
				String t = valueArray[i];
				message.append("\"");
				message.append(t);
				message.append("\"");
				if (i < (length - 1)) {
					message.append(",");
				}
			}
		}
		message.append("]之中！");
		return message.toString();
	}

	@Override
	public String getKey() {
		return "inStringArray";
	}

	public <E> String[] getArray(E value) {
		String[] valueArray = {};
		if (value instanceof JSONArray) {
			JSONArray ja = (JSONArray) value;
			int size = ja.size();
			valueArray = new String[size];
			for (int i = 0; i < size; i++) {
				valueArray[i] = ja.getString(i);
			}
		}
		return valueArray;
	}

	public String getCode() {
		return ValidatorError.range_error;
	}

	public static final int INDEX_NOT_FOUND = -1;

	public static boolean contains(final Object[] array, final Object objectToFind) {
		return indexOf(array, objectToFind) != INDEX_NOT_FOUND;
	}

	public static int indexOf(final Object[] array, final Object objectToFind) {
		return indexOf(array, objectToFind, 0);
	}

	public static int indexOf(final Object[] array, final Object objectToFind, int startIndex) {
		if (array == null) {
			return INDEX_NOT_FOUND;
		}
		if (startIndex < 0) {
			startIndex = 0;
		}
		if (objectToFind == null) {
			for (int i = startIndex; i < array.length; i++) {
				if (array[i] == null) {
					return i;
				}
			}
		} else if (array.getClass().getComponentType().isInstance(objectToFind)) {
			for (int i = startIndex; i < array.length; i++) {
				if (objectToFind.equals(array[i])) {
					return i;
				}
			}
		}
		return INDEX_NOT_FOUND;
	}

}
